from aiogram import Router, F
from aiogram.filters import CommandStart, Command
from aiogram.types import Message, ReplyKeyboardRemove
from aiogram.fsm.context import FSMContext
from fluent.runtime import FluentLocalization

from recruit_bot.api.base import AbstractRequests
from recruit_bot.api.user import UserAPI
from recruit_bot.services.user import UserService

router = Router()


@router.message(CommandStart())
async def command_start(
        message: Message,
        l10n: FluentLocalization,
        api_url: str,
        requests: AbstractRequests
) -> None:
    user = UserService().create_user(
        message.from_user.username,
        message.from_user.id
    )
    await UserAPI().create_user(
        user=user,
        requests=requests,
        url=f'{api_url}/users/'
    )
    await message.answer(
        l10n.format_value(
            'start', args={
                'name': message.from_user.username
            }
        )
    )


@router.message(Command('help'))
async def command_help(message: Message, l10n: FluentLocalization) -> None:
    await message.answer(l10n.format_value('help'))


@router.message(Command('cancel'))
@router.message(F.text.casefold() == 'cancel')
async def command_cancel(
        message: Message,
        l10n: FluentLocalization,
        state: FSMContext
) -> None:
    current_state = await state.get_state()
    if current_state is None:
        return

    await state.clear()
    await message.answer(
        l10n.format_value('cancel'),
        reply_markup=ReplyKeyboardRemove()
    )
